package com.jnc.rest.core.interceptor;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;

/**
 * @Auther: jjn
 * @Date: 2020/1/17 15:56
 * @Desc: okHttp3 自定义重试拦截器
 */
public class RetryIntercepter implements Interceptor {

    public int maxRetryCount;
    private int count = 0;

    public RetryIntercepter(int maxRetryCount) {
        this.maxRetryCount = maxRetryCount;
    }


    @NotNull
    @Override
    public Response intercept(Chain chain) throws IOException {
        return retry(chain);
    }

    /**
     * 重试机制
     * @param chain
     * @return
     */
    private Response retry(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);
        while (!response.isSuccessful() && count < maxRetryCount) {
            count++;
            response = chain.proceed(request);
        }
        return response;
    }
}
